from datetime import datetime
from utils.file_handler import FileHandler
from models.exercise import Exercise
import time

class Teacher:
    def __init__(self):
        self.file_handler = FileHandler()
    
    def generate_exam(self, exam_id, question_count=50):
        """生成试卷"""
        # 创建练习对象
        exercise = Exercise(exam_id, question_count)
        # 生成题目
        exercise.generate_questions()
        # 保存试卷
        self.file_handler.save_exam(exam_id, exercise.to_dict())
        return exam_id
    
    def format_exam_questions(self, questions):
        """格式化试卷显示"""
        formatted = "\n试卷内容：\n" + "="*80 + "\n"
        
        # 每4个算式一行
        for i in range(0, len(questions), 4):
            line_questions = questions[i:i+4]
            # 算式部分
            question_line = ""
            # 答案部分
            answer_line = ""
            
            for j, q in enumerate(line_questions):
                # 保持每个算式占20个字符的宽度
                question = f"{i+j+1}. {q['question']}"
                answer = f"{i+j+1}. {q['question']}{q['answer']}"
                question_line += f"{question:<20}"
                answer_line += f"{answer:<20}"
            
            formatted += question_line + "\n"
            formatted += answer_line + "\n"
            formatted += "-"*80 + "\n"
        
        return formatted

    def grade_submission(self, submission_id):
        """批改答卷"""
        # 加载答卷
        submission = self.file_handler.load_submission(submission_id)
        if not submission:
            raise Exception("答卷不存在")
        
        # 加载原试卷
        exam = self.file_handler.load_exam(submission['exam_id'])
        if not exam:
            raise Exception("原试卷不存在")
        
        # 批改
        total_questions = len(exam['questions'])
        correct_count = 0
        results = []
        
        for student_answer, question in zip(submission['answers'], exam['questions']):
            is_correct = student_answer.strip() == question['answer'].strip()
            if is_correct:
                correct_count += 1
            results.append(is_correct)
        
        # 计算得分
        score = round(100 * correct_count / total_questions, 1)
        
        # 保存结果
        result_data = {
            'exam_id': submission['exam_id'],
            'student_name': submission['student_name'],
            'score': score,
            'results': results,
            'timestamp': time.strftime("%Y-%m-%d %H:%M:%S")
        }
        
        self.file_handler.save_results(submission_id, result_data)
        return score